package daoimpl;

import java.util.ArrayList;

import nu.xom.Attribute;
import nu.xom.Element;
import nu.xom.Elements;
import dao.Dao;
import domain.Person;

public class PersonDaoImpl extends Dao<Person> {

	public PersonDaoImpl() {
		super("xmlDB/persons/persons.xml", "xmlDB/persons/idSequence.xml");
	}
	
	private Person elementToPerson(Element e) {
		Person person = new Person();
		int id = Integer.parseInt(e.getAttribute("id").getValue());
		String name = e.getChildElements("name").get(0).getValue();
		person.setId(id);
		person.setName(name);
		return person;
	}
	
	private Element personToElement(Person person) {
		Element e = new Element("person");
		e.addAttribute(new Attribute("id", ""+person.getId()));
		Element name = new Element("name");
		name.appendChild(""+person.getName());
		e.appendChild(name);
		return e;
	}
	
	public Person add(Person person) {
		person.setId(this.idSequence++);
		document.getRootElement().appendChild(personToElement(person));
		documentChanged = true;
		return person;
	}

	public Person find(int id) {
		Elements persons = document.getRootElement().getChildElements();
		for (int i = 0; i < persons.size(); i++) {
			Element person = persons.get(i);
			if (Integer.parseInt(person.getAttribute("id").getValue()) == id) {
				return elementToPerson(person);
			}
		}
		return null;
	}

	public ArrayList<Person> listAll() {
		ArrayList<Person> res = new ArrayList<Person>();
		Elements persons = document.getRootElement().getChildElements();
		for (int i = 0; i < persons.size(); i++) {
			Element person = persons.get(i);
			res.add(elementToPerson(person));
		}
		return res;
	}

	public Person remove(int id) {
		Elements persons = document.getRootElement().getChildElements();
		for (int i = 0; i < persons.size(); i++) {
			Element person = persons.get(i);
			if (Integer.parseInt(person.getAttribute("id").getValue()) == id) {
				document.getRootElement().removeChild(person);
				return elementToPerson(person);
			}
		}
		return null;
	}

	public Person update(Person person) {
		Elements persons = document.getRootElement().getChildElements();
		for (int i = 0; i < persons.size(); i++) {
			Element personElement = persons.get(i);
			if (Integer.parseInt(personElement.getAttribute("id").getValue()) == person.getId()) {
				document.replaceChild(personElement, personToElement(person));
				return person;
			}
		}
		return null;
	}

}